import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { withRouter, Route } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { Button, Result, Icon, SearchBar, Popover, Tools, Modal } from 'weaver-mobile';
import { RouteLayout, ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderNoSearch, renderHeader } from '../util';
import NewVote from './New';
import Vote from './Vote';

const getLabel = Tools.getLabel;
const alert = Modal.alert;

@withRouter
@inject('groupVoteStore')
@observer
class GroupVoteList extends Component {
  static defaultProps = {
    prefixCls: 'group-vote-list'
  }

  componentDidMount () {
    const { groupVoteStore: { getGroupVoteList } } = this.props;
    getGroupVoteList();
  }

  renderNoData = (history, newVoteLayout) => (
    <div className='group-vote-noData' key='nodata'>
      <Result
        img={<Icon type="document-report" />}
        message={<div>
          <p>暂无投票，快去发布投票吧</p>
          <Button type='primary' onClick={() => history.push(newVoteLayout.path)}>发布新投票</Button>
        </div>}
      />
      { this.renderRoute() }
    </div>
  )

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = `${this.props.prefixCls}-item`;
          return (
            <div className={curCls} key={data.id}>
              { renderHeader(data) }
              <div className={`${curCls}-container`}>
                <div className={`${curCls}-container-theme`}>{data.votethemespan}</div>
                {data.themeimageidspan !== '' && (
                  <div className={`${curCls}-container-themeImage`}><img alt='' src={data.themeimageidspan}/></div>
                )}
                <div className={`${curCls}-container-bottomInfo`}>
                  <span className={`${curCls}-container-cutoff`}>截止时间：{`${data.enddatespan} ${data.endtimespan}`}</span>
                  <span className={`${curCls}-container-delete`} onClick={(e) => this.deleteVote(e, data)}><Icon type='delete' size='xxs'/></span>
                </div>
              </div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderSeparator = (section, index) => {
    const { groupVoteStore, prefixCls } = this.props;
    const { voteList, shareChoose } = groupVoteStore;
    const data = toJS(voteList.data)[index];
    return (
      <div className={`${prefixCls}-item-bottom-wrap`} key={`${section}_${index}`}>
        {!shareChoose && (
          <div className={`${prefixCls}-item-bottom`} onClick={() => this.onRowClick(data)}>
            { data.votestatus === '0' ? <a>立即投票</a> : <a>已投票，查看结果</a> }
          </div>
        )}
      </div>
    )
  }

  /* 删除投票 */
  deleteVote = (e, data) => {
    e.preventDefault();
    e.stopPropagation();
    const { groupVoteStore } = this.props;
    const { groupchatvotedel } = groupVoteStore;
    alert('确定要删除该投票吗？', '', [
      { text: '取消' },
      { text: '确定', onPress: () => groupchatvotedel({votingid: data.id}) }
    ])
  }

  onExtraButtonClick = (key) => {
    const { groupVoteStore } = this.props;
    const { setStoreState } = groupVoteStore;
    if (key === 'drop') {
      setStoreState({shareVisible: true})
    }
  }

  onSelect = (opt) => {
    const { groupVoteStore } = this.props;
    const { setStoreState } = groupVoteStore;
    if (opt.key === 'batch') {
      setStoreState({shareVisible: false, shareChoose: true});
    }
  }

  /* 批量分享 */
  handleShare = (selectedRowKeys) => {
    const { groupVoteStore } = this.props;
    const { groupchatvotealert } = groupVoteStore;
    alert('确定要分享所选投票吗？', '', [
      { text: '取消' },
      { text: '确定', onPress: () => groupchatvotealert({votingid: selectedRowKeys.join(), isgroup: 0, groupid: ''}) },
    ])
  }

  /* 行点击事件 */
  onRowClick = (rowData) => {
    const { history, groupVoteStore: { votingLayout } } = this.props;
    history.push(`${votingLayout.path}/${rowData.id}`)
  }

  render () {
    const { prefixCls, history, groupVoteStore } = this.props;
    const { newVoteLayout, setStoreState, voteListLoading, shareVisible } = groupVoteStore;
    const { voteList, doShareCancel, doShareSelectAll, doShareSelectNone, getGroupVoteList, shareChoose, isSearch  } = groupVoteStore;
    const datas = toJS(voteList.data);
    const themeSelectedKeys = toJS(voteList.selectedRowKeys);
    const more = (
      <Popover
        mask
        visible={shareVisible}
        overlay={[<Popover.Item key='batch' >批量操作</Popover.Item>]}
        onVisibleChange={v => setStoreState({shareVisible: v})}
        onSelect={this.onSelect}
      >
        <Icon key="ellipsis" type="ellipsis" />
      </Popover>
    )
    const extraButton = [{ key: 'drop', show: more }];
    const listCls = classnames({
      [`${prefixCls}-container`]: true,
      'showCheck': shareChoose,
    });
    if (voteListLoading) return renderLoading;
    if (datas.length === 0 && !isSearch) return this.renderNoData(history, newVoteLayout);
    return (
      <div className={prefixCls}>
        <SearchBar 
          placeholder={'请输入群投票名称'}
          showExtraButton
          extraButton={extraButton}
          onExtraButtonClick={this.onExtraButtonClick}
          onSubmit={v => {getGroupVoteList({groupvotename: v}); setStoreState({isSearch: true})}}
        />
        {
          shareChoose && (
            <div className={`${prefixCls}-top`}>
              <span className={`${prefixCls}-top-cancel`} onClick={doShareCancel}>{getLabel(201, '取消')}</span>
              <span>{getLabel(31503,"已选择")}{themeSelectedKeys.length}{'条记录'}</span>
              {themeSelectedKeys.length !== datas.length ?
                <span className={`${prefixCls}-top-all`} onClick={doShareSelectAll}>{getLabel(556, '全选')}</span> :
                <span className={`${prefixCls}-top-all`} onClick={doShareSelectNone}>{getLabel(387379,"取消全选")}</span>
              }
            </div>
          )
        }
        <div className={listCls}>
          {
            datas.length === 0 && isSearch ? renderNoSearch() : (
              <ListViewPage.Normal
                store={voteList}
                customHeight={'100%'}
                showCheck={shareChoose}
                getTemplate={this.getTemplate}
                renderSeparator={this.renderSeparator}
                onRowClick={this.onRowClick}
              />
            )
          }
        </div>
        <div className={`${prefixCls}-publish`}>
          {
            shareChoose ? <Button type='primary' onClick={() => this.handleShare(themeSelectedKeys)}>批量分享</Button> :
            <Button type='primary' onClick={() => history.push(newVoteLayout.path)}>发布新投票</Button>
          }
        </div>
        { this.renderRoute() }
      </div>
    )
  }

  /* 页面路由 */
  renderRoute = () => {
    const { groupVoteStore } = this.props;
    const { newVoteLayout, votingLayout, votedLayout } = groupVoteStore;
    return (
      <div className='group-vote-router'>
        <Route
          key={newVoteLayout.id}
          path={newVoteLayout.path}
          render={() => (
            <RouteLayout>
              <div key="newVote" className="wm-route-layout">
                <NewVote/>
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={votingLayout.id}
          path={`${votingLayout.path}/:id`}
          render={() => (
            <RouteLayout>
              <div key="voting" className="wm-route-layout">
                <Vote />
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={votedLayout.id}
          path={`${votedLayout.path}/:id`}
          render={() => (
            <Vote isVoted />
          )}
        />
      </div>
    )
  }
}

export default GroupVoteList